package logic

import (
	"C/renrenzhuC_srv/internal/svc"
	"C/renrenzhuC_srv/model/mysql"
	"C/renrenzhuC_srv/pkg"
	"C/renrenzhuC_srv/renrenzhuC"
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *renrenzhuC.OrderAddRequest) (*renrenzhuC.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	var g mysql.Goods
	err := mysql.DB.Where("id", in.GoodsId).Find(&g).Error
	if err != nil {
		logx.Error("没有该商品")
		return nil, fmt.Errorf("没有该商品")
	}
	if g.Stock < in.Num {
		logx.Error("商品库存不足")
		return nil, fmt.Errorf("商品库存不足")
	}
	OrderId := uuid.NewString()
	var o = mysql.Order{
		UserId:  int(in.UserId),
		OrderId: OrderId,
		Amount:  g.Price * float64(in.Num),
		Payment: "1",
		Status:  "1",
	}
	var og = mysql.OrderGoods{
		OrderId: int(o.ID),
		GoodsId: int(in.GoodsId),
		Title:   g.Title,
		Price:   g.Price,
		Cover:   g.Cover,
		Stock:   int(g.Stock),
		Status:  g.Status,
		Likes:   g.Likes,
		Type:    g.Type,
	}
	mysql.CreateAnimals(&o, &og)
	pay := pkg.NewAlipay().Pay(g.Title, o.OrderId)
	return &renrenzhuC.OrderAddResponse{
		Success: true,
		Url:     pay,
	}, nil
}
